/**
@author : MAMAMA
@date: 2019-07-12
@description: control panasonic dc motor
*/

#include "Briter.h"
#include <math.h>

extern void modbus_delay(uint32_t t);

/* Global Variables --------------------------------------------------*/

/**
  * @brief  电机modbus初始化
  * @param  axisid: 轴编号（modbus地址），pstream: 串口通信类地址，pmodbus: modbus节点类地址
  * @retval None
  */
Briter::Briter(uint8_t axisid, Stream *pstream) : _pstream(pstream), axis_id(axisid)
{
    _pmodbus_master = new ModbusMaster();
    _connect_state = OFFLINE;
    status = 0x00;
}

Briter::~Briter(void)
{
    delete _pmodbus_master;
}

bool Briter::connectOnce(void)
{
    uint8_t retcode;
    uint16_t cnt = 0;
    bool ret = false;
    
    if(status==0x00)
    {
        retcode = _pmodbus_master->readHoldingRegisters(BRT_SINGLE_PULSE, 1);
        modbus_delay(MODBUS_INTERVAL);
        if (retcode == 0)
        {
            status = 1U;
            single_turn = _pmodbus_master->getResponseBuffer(0);
            _pmodbus_master->modbus_error_cnt = 0;  //连上之后清除错误计数
            _connect_state = ONLINE;
            ret = true;
        }
    }
    else
        ret = true;
    
    if(_pmodbus_master->modbus_error_cnt > 100)
    {
        _connect_state = OFFLINE;
        status = 0x00;
        ret = false;
    }
    
    return ret;
}

/**
@description send a modbus request to the motor,
recieving the correct responce means connecting success.
@return true: connecting success
        false: connecting failure
*/
bool Briter::initModbus(void)
{
    bool ret = false;
    if (_connect_state == OFFLINE)
    {
        _pmodbus_master->begin(axis_id, *_pstream);
        /**
        do some modbus task here
        */
        //获取编码器信息
        if(this->connectOnce())
        {
            ret = true;
            _connect_state = ONLINE;
        }
        return ret;
    }
    else
    {
        return true;
    }
}

bool Briter::getTurns()
{
    uint8_t retcode = 0xFF;
    if(_connect_state == ONLINE)
    {
        retcode = _pmodbus_master->readHoldingRegisters(BRT_TURNS, 2);
        modbus_delay(MODBUS_INTERVAL);
        if (retcode == 0)
        {
            this->turns = _pmodbus_master->getResponseBuffer(0);
            this->single_turn = _pmodbus_master->getResponseBuffer(1);
            return true;
        }
        else
            return false;
    }
    else
        return false;
 
}

